<template>
  <el-dialog :title="title" :visible="validate" @closed="closedHandler">
    <el-form ref="form" :model="form" :rules="rules">
      <el-form-item prop="name" label="角色名称" :label-width="formLabelWidth">
        <el-input v-model="form.name" autocomplete="off" />
      </el-form-item>
      <el-form-item
        prop="description"
        label="角色描述"
        :label-width="formLabelWidth"
      >
        <el-input v-model="form.description" autocomplete="off" />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogFormVisible = false">取 消</el-button>
      <el-button type="primary" @click="submitForm">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { addRole, editRoleById } from '../../../api/setting'
export default {
  name: 'SettingDialog',
  data() {
    return {
      // 是否打开弹框
      validate: false,
      formLabelWidth: '120px',
      form: {
        name: '',
        description: ''
      },
      //   表单校验
      rules: {
        name: [
          { required: true, message: '角色名称不能为空', trigger: 'blur' }
        ],
        description: [
          {
            required: true,
            message: '角色描述不能为空.ღ( ´･ᴗ･` )比心',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  computed: {
    title() {
      return this.form.id ? '修改尼玛呢' : '新增尼玛呢'
    }
  },
  methods: {
    closedHandler() {
      this.form = {
        name: '',
        description: ''
      }
    },
    //   点击确认按钮
    submitForm() {
      this.$refs.form.validate(async valid => {
        if (valid) {
          // 判断走那个逻辑
          if (this.form.id) {
            // 修改
            await editRoleById(this.form)
            this.$message.success('修改成功')
          } else {
            //   新增
            await addRole(this.form)
            this.$message.success('新增成功')
          }
          //  关闭
          this.validate = false
          //   清空
          this.form = {
            name: '',
            description: ''
          }
          // 从新获取数据
          this.$parent.getData()
        } else {
          //   失败
          this.$message.error('新增失败')
          this.validate = false
        }
      })
    }
  }
}
</script>

<style></style>
